package com.csu.bailan.controller;

import com.csu.bailan.common.CONSTANT;
import com.csu.bailan.common.CommonResponse;
import com.csu.bailan.common.ResponseEnum;
import com.csu.bailan.domain.Address;
import com.csu.bailan.domain.Signon;
import com.csu.bailan.domain.User;
import com.csu.bailan.dto.AddrDTO;
import com.csu.bailan.dto.UpdateUserDTO;
import com.csu.bailan.service.CartService;
import com.csu.bailan.service.UserService;
import com.csu.bailan.util.MD5Util;
import com.csu.bailan.vo.RegVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CartService cartService;

    @PostMapping("login")
    public CommonResponse<User> login(@RequestParam @Validated @NotBlank(message="用户名不能为空") String username,
                                      @RequestParam @Validated @NotBlank(message="密码不能为空") String password,
                                      HttpSession httpSession) throws Exception {
        System.out.println(username+"  "+password);
        CommonResponse<User> user = userService.getUserByUNandPW(username, password);
        if(user.isSuccess()){
            log.info(user.getData().toString());
            httpSession.setAttribute(CONSTANT.LOGIN_USER , user.getData());
        }
        return user;
    }

    @GetMapping("logout")
    public CommonResponse<String> logout(HttpSession session){
        session.removeAttribute(CONSTANT.LOGIN_USER);
        return CommonResponse.createForSuccessMessage("退出登录成功");
    }

    @PostMapping("register")
    public CommonResponse<User> register(RegVO regVO, HttpSession httpSession) throws Exception {
        System.out.println(regVO.toString());
        User user = userService.getUserByUsername(regVO.getUsername());
        if (user != null){
            log.error("用户已存在");
            return CommonResponse.createForError(ResponseEnum.UserExistERROR.getCode(), ResponseEnum.UserExistERROR.getMessage());
        }
        user = new User();
        user.setNickname(nicknameGenerate());
        user.setUsername(regVO.getUsername());
        user.setPhone(regVO.getPhone());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        Signon signon = new Signon();
        Map<String, String> map = MD5Util.getEncryptedPwd(regVO.getPassword());
        signon.setSalt(map.get("salt"));
        signon.setPassword(map.get("ep"));
        CommonResponse<User> result = userService.createUser(user, signon);
        if(result.isSuccess()){
            cartService.createCart(user.getUserId());
            log.info("完成用户创建");
            return result;
        }
        else {
            log.error("用户创建失败");
            return result;
        }
    }

    @PostMapping("updatepassword")
    public CommonResponse<User> updatePassword(@RequestParam @Validated @NotBlank(message="用户名不能为空") String username,
                                               @RequestParam @Validated @NotBlank(message="密码不能为空") String newpassword1,
                                               @RequestParam @Validated @NotBlank(message="密码不能为空") String newpassword2) throws Exception {
        CommonResponse<User> result = userService.updatePassword(username,newpassword1,newpassword2);
        return result;
    }

    @PostMapping("updateInfo")
    public CommonResponse<User> updateInfo(UpdateUserDTO updateUserDTO){
        CommonResponse<User> result = userService.updateUserInfo(updateUserDTO);
        return result;
    }

    @PostMapping("deleteuserbyid")
    public CommonResponse<User> deleteUserByID(String userid){
        CommonResponse<User> result = userService.deleteUserByUserid(userid);
        return result;
    }

    @PostMapping("deleteuserbyname")
    public CommonResponse<User> deleteUserByName(String username){
        CommonResponse<User> result = userService.deleteUserByUsername(username);
        return result;
    }

    @PostMapping("updateAddr")
    public CommonResponse<Address> updataAddrByUid(AddrDTO addrDTO){
        return userService.updateAddr(addrDTO);
    }

    @PostMapping("createAddr")
    public CommonResponse<Address> createAddr(AddrDTO addrDTO){
        return userService.newAddr(addrDTO);
    }

    public static String nicknameGenerate(){
        Date date = new Date();
        return "bailan_"+ UUID.randomUUID().toString().trim().replaceAll("-","");
    }
}
